<?php
include_once dirname(__FILE__)."/../../core/constants.php";
include_once dirname(__FILE__)."/../../core/mainpage.php";
include_once dirname(__FILE__)."/../../core/database.php";
include_once dirname(__FILE__)."/../../core/safe.php";
include_once dirname(__FILE__)."/../../core/game_management/users.php";

class LoginPage extends MainPage
{
    function LoginPage()
    {
        $strBlock = "";
        
        if(isset($_POST["tbxUserName"]) && isset($_POST["tbxPassword"]))
        {
            $userName = safePost("tbxUserName");
            $password = safePost("tbxPassword");
            
            if(strlen($userName) && strlen($password))
            {
                if(User::login($userName, $password))
                {
                    header("location: ".createUrl("pages/game/index.php"));
                }
                else
                {
                    $strBlock = $this->showLoginPage("ERRORE: Nome utente errato!");
                }
            }
            else
            {
                $strBlock = $this->showLoginPage("ATTENZIONE: Compila tutti i campi!");
            }
        }
        else
        {
            $strBlock = $this->showLoginPage("");
        }
        
        parent::MainPage("Login", $strBlock);
    }
    
    private function showLoginPage($msg)
    {
        $tbxUserName = new HTMLInput("text", "tbxUserName", "");
        $tbxPassword = new HTMLInputPassword("tbxPassword");
        
        $cell1 = new HTMLTableCell("UserName:");
        $cell1->setAttribute("align", "right");
        $cell2 = new HTMLTableCell($tbxUserName);
        $row1 = new HTMLTableRow(array($cell1, $cell2));
        
        $cell1 = new HTMLTableCell("Password:");
        $cell1->setAttribute("align", "right");
        $cell2 = new HTMLTableCell($tbxPassword);
        $row2 = new HTMLTableRow(array($cell1, $cell2));
        
        $regTable = new HTMLTable(array($row1, $row2));
        $msg = "Inserisci Username e Password:<br/><br/>";
        $lnkRecoverPass = new HTMLAnchor(createUrl("pages/login/recover_password.php"), "Hai dimenticato la password?");
        $btnRegister = new HTMLInputSubmitButton("Login", "btnLogin");
        
        $frm = new HTMLForm($msg.$regTable->render()."<br/>".$lnkRecoverPass->render()."<br/><br/>".$btnRegister->render(), createUrl("pages/login/index.php"), "POST");
        $pageText .= $frm->render();
        
        $block = new HTMLBlock($pageText);
        $block->setAttribute("align", "center");
        
        return $block->render();
    }
}

$p = new LoginPage();
$ws = new WebPage("Login", $p);
echo $ws->render();
?>
